// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI)
import Axios from './common/axios'
import Vuex from 'vuex'
Vue.use(Vuex)
// 保证刷新之后，vuex的userInfo还有值
let userInfo = JSON.parse(localStorage.getItem('userInfo')) || {}
const store = new Vuex.Store({
  state: {
    username: 'admin',
    userInfo: userInfo
  },
  mutations: {
    // 记录用户信息
    setUserInfo(state, payload) {
      state.userInfo = payload;
      // localStorage也存一份
      localStorage.setItem('userInfo', JSON.stringify(payload))
    }
  }
});
// 添加到vue实例上，方便全局使用
Vue.prototype.$axios = Axios
Vue.prototype.$host = 'http://localhost:3000/'
Vue.config.productionTip = false

router.beforeEach((to, from, next) => {
  document.title = to.meta.title || '后台管理系统';
  // 获取登录信息
  let userInfo = JSON.parse(localStorage.getItem('userInfo'));
  if(userInfo) {
    // 已登录
    next();
  }else {
    // 未登录
    if(to.path === '/login') {
      // 地址是登录页，就正常跳转
      next();
    }else {
      // 地址不是登录页，就先去登录页
      next('/login');
    }
  }
})
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  store,
  template: '<App/>'
})
